package com.zyasdk.service;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.zhuoyian.analysis.service.WebService;
import com.zhuoyian.analysis.util.AppUtils;
import com.zhuoyian.analysis.util.StaticSettings;
import com.zyasdk.model.ARModel;
import com.zyasdk.util.JSONHelper;
import com.zyasdk.util.res.CRUtil;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class VersionService {

	Context context;

	public VersionService(Context context) {
		this.context = context;
	}

/**
 * 
 * @param handler
 */
	public void GetNewVersions(Handler handler) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("PBindKey",StaticSettings.getKey()));
		params.add(new BasicNameValuePair("vcode", ""+ AppUtils.getVersionCode(context)));
		params.add(new BasicNameValuePair("id", AppUtils.getRawFileContent(context, CRUtil.getRawId(context, "p"))));
		getJsonObjectRequest(GetAPIUrl("package"), handler, params);
//		http://test.zhuoyian.com/Api/package?PBindKey=&id=&vcode=
		
		Log.i("ConHandler", "model="+GetAPIUrl("package")+"?"+params.toString());
	}
	
	/**
	 * 
	 * @param object
	 * @return
	 */
	public ARModel getARModel(JSONObject object) {
		ARModel model = null;
		try {
			if (object != null) {
				model = JSONHelper.parseObject(object, ARModel.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return model;
	}

	public String GetAPIUrl(String Method) {
		return StaticSettings.getServerPath() + "Api/" + Method;
	}

	public synchronized void getJsonObjectRequest(final String url,
			final Handler handler, final List<NameValuePair> param) {
		new Thread() {
			public void run() {
				try {
					String json = WebService.GetResponse(url, param);
					Log.i("result", "run + VersionService" + json);
					if (json != null) {
						JSONObject object = new JSONObject(json);
						ARModel model = getARModel(object);
						Bundle bundle = new Bundle();
						bundle.putSerializable("result", model);
						Message message = new Message();
						message.what = StaticSettings.RESULT_OK;
						message.setData(bundle);
						handler.sendMessage(message);
					} else {
						handler.sendEmptyMessage(StaticSettings.RESULT_ERROR);
					}
				} catch (Exception e) {
					handler.sendEmptyMessage(StaticSettings.RESULT_ERROR);
					e.printStackTrace();
				}
			}
		}.start();
	}

}
